package com.qing.common_result.result;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

//请求拦截器
@Slf4j
@Component
public class ResponseResultInterceptor implements HandlerInterceptor {


	//    代码核心思想，就是获取此请求，是否需要返回值包装，设置一个属性标记。
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("-------------进入拦截器打标记------");
		if (handler instanceof HandlerMethod) {
			final HandlerMethod handlerMethod = (HandlerMethod) handler;
			final Class<?> clazz = handlerMethod.getBeanType();
			final Method method = handlerMethod.getMethod();
			//判断是否在类对象上加了注释
			if (clazz.isAnnotationPresent(ResponseResult.class)) {
				//设置此请求返回体，需要包装，往下传递，在ResponseBodyAdvice接口进行判断
				request.setAttribute(CommonFinal.RESPONSE_RESULT_ANN, clazz.getAnnotation(ResponseResult.class));
			}
			//判断方法上是否有注释
			else if (method.isAnnotationPresent(ResponseResult.class)) {
				//设置此请求返回体，需要包装，往下传递，在ResponseBodyAdvice接口进行判断
				request.setAttribute(CommonFinal.RESPONSE_RESULT_ANN, method.getAnnotation(ResponseResult.class));
			}

		}
		return true;
	}

}
